package cn.bnjy.controller;

import cn.bnjy.common.WeiXinAccessToken;
import cn.bnjy.common.WeiXinApi;
import cn.bnjy.common.WeiXinConstant;
import cn.bnjy.core.Result;
import cn.bnjy.entity.BaseMessage;
import cn.bnjy.service.IMessageService;
import cn.bnjy.util.HttpUtils;
import cn.bnjy.util.MessageFormatUtils;
import cn.bnjy.util.WXUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Map;

/**
 * 描述：微信控制器
 *
 * @author chavin
 * @since 2018-11-07 00:33:51
 */
@RequestMapping("/")
@RestController
@Slf4j
public class WeiXinController {

    @Autowired
    private IMessageService messageService;

    @GetMapping(value = "wx")
    public String verifyWXToken(HttpServletRequest request) throws IOException {
        // 微信加密签名
        String signature = request.getParameter("signature");
        // 时间戳
        String timestamp = request.getParameter("timestamp");
        // 随机数
        String nonce = request.getParameter("nonce");
        // 随机字符串
        String echostr = request.getParameter("echostr");
        log.info("校验token，signature: {}, timestamp: {}, nonce: {}, echostr: {}", signature, timestamp, nonce, echostr);
        // 通过检验signature对请求进行校验，若校验成功则原样返回echostr，表示接入成功，否则接入失败
        if (WXUtils.verifyToken(signature, timestamp, nonce)) {
            return echostr;
        }
        return null;
    }

    @PostMapping(value = "wx")
    public void core(HttpServletRequest request, HttpServletResponse response) throws IOException {
        PrintWriter out = response.getWriter();
        response.setCharacterEncoding("utf-8");
        request.setCharacterEncoding("utf-8");
        try {
            //接受微信服务器发送过来的XML形式的消息
            Map<String, String> params = MessageFormatUtils.xml2Map(request);
            log.info("接收微信消息：{}", params);
            BaseMessage baseMessage = messageService.message(params);
            String result = "";
            if(baseMessage != null) {
                result = MessageFormatUtils.obj2Xml(baseMessage);
                log.info("返回微信消息：\n{}", result);
            }
            out.print(result);
            out.close();
        } catch (Exception e) {
            log.error("处理微信消息异常：{}", e);
        }
    }

    @PostMapping(value="kf/add")
    public Result addKfAccount(@RequestBody Map<String, Object> map) {
        String result;
        try {
            log.info("添加客服账号：{}", JSON.toJSONString(map));
            result = HttpUtils.post(WeiXinApi.ADD_KF_ACCOUNT.replace(WeiXinConstant.ACCESS_TOKEN, WeiXinAccessToken.getToken()), map);
            JSONObject obj = JSON.parseObject(result);
            if("0".equals(obj.get("errcode"))) {
                result = "添加账号成功";
            }
            return Result.success(result);
        } catch (Exception e) {
            log.error("添加客服账号异常：", e);
            result = "添加客服账号发生异常";
        }
        return Result.error("添加客服账号失败：{}", result);
    }

    /**
     * 获取token
     * @return
     */
    @GetMapping(value="token")
    public Result token() {
        return Result.success(WeiXinAccessToken.getToken());
    }

}
